// 存储历史记录
let siteHistory = [];
let sourceHistory = [];

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadCurrentSiteInfo();
    loadSiteHistory();
    loadSourceHistory();
});

// 加载当前网站信息
function loadCurrentSiteInfo() {
    // 从存储中获取点击图标时的源标签页信息
    chrome.storage.local.get(['currentSourceTab'], function(result) {
        if (result.currentSourceTab) {
            displayCurrentSiteInfo(result.currentSourceTab);
            // 使用完后清除存储
            chrome.storage.local.remove(['currentSourceTab']);
        } else {
            document.getElementById('currentSiteInfo').innerHTML =
                '<p class="error">无法获取来源网站信息</p>';
        }
    });
}

// 显示当前网站信息
function displayCurrentSiteInfo(tabInfo) {
    const siteInfoDiv = document.getElementById('currentSiteInfo');
    const url = new URL(tabInfo.url);

    siteInfoDiv.innerHTML = `
        <div class="site-details">
            <div class="detail-item">
                <strong>标题:</strong> ${tabInfo.title || '无标题'}
            </div>
            <div class="detail-item">
                <strong>域名:</strong> ${tabInfo.hostname || url.hostname}
            </div>
            <div class="detail-item">
                <strong>协议:</strong> ${url.protocol.replace(':', '')}
            </div>
            <div class="detail-item">
                <strong>路径:</strong> ${url.pathname}
            </div>
            <div class="detail-item">
                <strong>完整 URL:</strong> ${tabInfo.url}
            </div>
            <div class="detail-item">
                <strong>点击时间:</strong> ${new Date(tabInfo.timestamp).toLocaleString('zh-CN')}
            </div>
        </div>
    `;
}

// 加载网站历史记录
function loadSiteHistory() {
    chrome.storage.local.get(['siteHistory'], function(result) {
        siteHistory = result.siteHistory || [];
        displayHistory();
    });
}

// 加载来源记录
function loadSourceHistory() {
    chrome.runtime.sendMessage({ action: 'getSourceRecords' }, function(response) {
        if (response && response.sourceHistory) {
            sourceHistory = response.sourceHistory;
            displayHistory();
        }
    });
}

// 显示历史记录（包含普通历史和来源记录）
function displayHistory() {
    const historyDiv = document.getElementById('siteHistory');

    // 合并所有记录并按时间排序
    const allRecords = [];

    // 添加普通历史记录
    siteHistory.forEach((site, index) => {
        allRecords.push({
            ...site,
            type: 'normal',
            originalIndex: index
        });
    });

    // 添加来源记录
    sourceHistory.forEach((source, index) => {
        allRecords.push({
            ...source,
            type: 'source',
            originalIndex: index
        });
    });

    // 按时间排序（最新的在前）
    allRecords.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));

    if (allRecords.length === 0) {
        historyDiv.innerHTML = '<p class="empty">暂无历史记录</p>';
        return;
    }

    const historyHTML = allRecords.map((record, index) => {
                const visitTime = new Date(record.timestamp).toLocaleString('zh-CN');
                const typeLabel = record.type === 'source' ? '🔗 来源记录' : '📋 普通访问';
                const typeClass = record.type === 'source' ? 'source-record' : 'normal-record';

                return `
            <div class="history-item ${typeClass}" data-url="${record.url}" data-index="${index}" data-type="${record.type}" data-original-index="${record.originalIndex}">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
                    <h3 style="margin: 0;">${record.title || '无标题'}</h3>
                    <span style="font-size: 0.8em; color: #667eea; font-weight: bold;">${typeLabel}</span>
                </div>
                <p><strong>域名:</strong> ${record.hostname}</p>
                <p><strong>时间:</strong> ${visitTime}</p>
                ${record.tabId ? `<p><strong>标签页 ID:</strong> ${record.tabId}</p>` : ''}
                <p><strong>URL:</strong> ${record.url}</p>
            </div>
        `;
    }).join('');

    historyDiv.innerHTML = historyHTML;

    // 添加点击事件
    const historyItems = document.querySelectorAll('.history-item');
    historyItems.forEach(item => {
        item.addEventListener('click', function() {
            const url = this.getAttribute('data-url');
            const type = this.getAttribute('data-type');
            const originalIndex = parseInt(this.getAttribute('data-original-index'));

            // 打开网站
            chrome.tabs.create({ url: url });

            // 更新访问时间（仅对普通历史记录）
            if (type === 'normal') {
                siteHistory[originalIndex].timestamp = new Date().toISOString();
                chrome.storage.local.set({ siteHistory: siteHistory });
                
                // 重新显示历史记录
                displayHistory();
            }
        });
    });
}



// 添加一些 CSS 样式
const style = document.createElement('style');
style.textContent = `
    .error {
        color: #dc3545;
        text-align: center;
        font-weight: bold;
    }
    
    .empty {
        text-align: center;
        color: #6c757d;
        font-style: italic;
        padding: 20px;
    }
`;
document.head.appendChild(style);